package com.terren.spider.run;

import java.util.ArrayList;
import java.util.List;

import com.terren.spider.db.service.SpiderWebTestTaskService;
import com.terren.spider.db.service.WebTestResultService;
import com.terren.spider.entity.biz.WebTestResult;
import com.terren.spider.entity.core.Entry;
import com.terren.spider.entity.core.SpiderWebTestTask;
import com.terren.spider.entity.core.WebTest;
import com.terren.spider.handler.impl.HtmlSpiderHandlerImpl;
import com.terren.spider.run.basic.BasicSpiderRunner;
import com.terren.spider.util.common.CommonUtil;
import com.terren.spider.util.common.JSONUtil;
import com.terren.spider.util.common.LogUtil;

public class SpiderWebTestRunner extends BasicSpiderRunner<WebTestResult> {

	protected SpiderWebTestTaskService spiderWebTestTaskService;// 扒取任务service
	protected SpiderWebTestTask tasks;//taskid 状态：  0 等待抓取   1抓取完成 -1抓取失败   9 抓取正在进行
	protected WebTestResultService WebTestResultService;
   
	public SpiderWebTestRunner() {
		super();
		spiderWebTestTaskService = CommonUtil.getBean(SpiderWebTestTaskService.class);
		WebTestResultService = CommonUtil.getBean(WebTestResultService.class);
	}

	@Override
	public List<Entry> getEntrys() {
		List<Entry> entries = new ArrayList<>();
		
		try {
			tasks = spiderWebTestTaskService.getOneSpiderTask();//找到spider任务
			if (null!= tasks) {
				tasks.setStatus(9);//状态设成 9 表示正在运行
				spiderWebTestTaskService.updateStatus(tasks);//状态设成 9 表示正在运行
				entries = JSONUtil.fromJsonList(tasks.getConfig(),Entry.class);
			}
		} catch (Exception e) {
			LogUtil.logger.error("SpiderWebTestRunner error", e);
			taskFaild();
		}
		
		return entries;
	}

	@Override
	public void postInitEntry(Entry entry) throws Exception {
		
	}
	
	public void runTask() {
		while (true) {
			try {
				run();
				Thread.sleep(5000);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("runTask error",e);
				taskFaild();
			}
		}
	}
	
	public void taskFaild() {
		if (tasks!=null) {
			tasks.setStatus(-1);//状态设成 1 表示完成
			try {
				spiderWebTestTaskService.updateStatus(tasks);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	@Override
	public void postRun(Entry entry) {
		if (tasks!=null) {
			tasks.setStatus(1);//状态设成 1 表示完成
			try {
				spiderWebTestTaskService.updateStatus(tasks);
				WebTest test = new WebTest();
				test.setTaskId(tasks.getTaskId());
				test.setResultItem(handler.getCollectItemsJson());
				test.setUrl(handler.getConfiguration().getEntry().getEntryUrl());
				WebTestResultService.save(test);
				
			} catch (Exception e) {
				log.error("runTask error",e);
			}
		}
	}

	@Override
	public HtmlSpiderHandlerImpl<WebTestResult> spiderHandler(Entry entry) throws Exception {
		// TODO Auto-generated method stub
		return new HtmlSpiderHandlerImpl<>(entry, WebTestResult.class);
	}
}
